#!/usr/bin/python

import os
import sys
import time
import socket
import shutil
import hashlib

WAIT_TIMEOUT = 10 # seconds

def write_node_file(sync_dir):
    node_str  = "%s_%s_%s" % (socket.gethostname(), os.getpid(), time.time())
    node_hash = hashlib.md5(node_str).hexdigest()
    f = open(os.path.join(sync_dir, node_hash), 'w')
    f.write(node_str)
    f.close()
    return node_hash

def main():
    nodes_num = int(sys.argv[1])
    sync_dir  = sys.argv[2]
    
    node_hash = write_node_file(sync_dir)
    time.sleep(WAIT_TIMEOUT)
    files = sorted(os.listdir(sync_dir))
    if len(files) != nodes_num:
        raise Exception("Not enough files to start: %s != %s" % (len(files), nodes_num))
    node_id = files.index(node_hash)
    print node_id


if __name__ == '__main__':
    main()

